package com.hibase.core.rule.service.rulemenu.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hibase.common.util.EntityUtil;
import com.hibase.core.mybatis.service.BaseServiceImpl;
import com.hibase.core.rule.constant.CommConstant;
import com.hibase.core.rule.constant.RuleType;
import com.hibase.core.rule.entity.rulemenu.RuleMenu;
import com.hibase.core.rule.entity.rulemenu.RuleMenuContent;
import com.hibase.core.rule.entity.rulemenu.vo.RuleMenuListVO;
import com.hibase.core.rule.mapper.rulemenu.RuleMenuMapper;
import com.hibase.core.rule.service.rulemenu.RuleMenuContentService;
import com.hibase.core.rule.service.rulemenu.RuleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 规则菜单表 服务实现类
 * </p>
 *
 * @author hufeng
 * @since 2019-06-10
 */
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class RuleMenuServiceImpl extends BaseServiceImpl<RuleMenuMapper, RuleMenu> implements RuleMenuService {

    @Autowired
    private RuleMenuContentService ruleMenuContentService;

    /**
     * 查询规则菜单表列表
     */
    @Override
    public List<RuleMenuListVO> selectRuleMenuList(String id) {

        // 查询规则菜单
        QueryWrapper<RuleMenu> queryWrapper = new QueryWrapper<>();

        if (StrUtil.isBlank(id)) {

            queryWrapper.isNull("parent_id");
        } else {

            queryWrapper.eq("parent_id", id);
        }

        List<RuleMenu> ruleMenus = super.list(queryWrapper);

        List<RuleMenuListVO> result = EntityUtil.transform(ruleMenus, RuleMenuListVO.class);

        if(CollUtil.isNotEmpty(result)){

            for(RuleMenuListVO ruleMenuListVO : result){

                ruleMenuListVO.setType(RuleType.RULE_TYPE_MENU.getName());
            }
        }

        // 上一级的层级
        BigDecimal lever = StrUtil.isBlank(id) ? BigDecimal.ZERO : super.getById(id).getChildQty();

        // 查询数据源/规则
        List<RuleMenuContent> contents = ruleMenuContentService.list(new QueryWrapper<RuleMenuContent>().eq("menu_id", id).orderByAsc("type"));

        if(CollUtil.isNotEmpty(contents)){

            for (RuleMenuContent content : contents) {

                RuleMenuListVO temp = new RuleMenuListVO();

                temp.setMenuName(content.getName());
                temp.setChildQty(BigDecimal.ZERO);
                temp.setId(content.getId());
                temp.setLevel(lever.add(BigDecimal.ONE));
                temp.setType(content.getType());
                temp.setStatus(content.getStatus());

                result.add(temp);
            }
        }

        return result;
    }

    /**
     * 改变规则菜单表记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRuleMenu(RuleMenu entity) {

        if (StrUtil.isBlank(entity.getId())) {

            entity.setChildQty(BigDecimal.ZERO);
        }

        // 查询到旧的记录
        RuleMenu old = null;
        if(StrUtil.isNotBlank(entity.getId())){

            old = super.getById(entity.getId());
        }

        super.store(entity);

        // 设置全路径及层级数、父节点数量加1
        this.settingsFullIds(old, entity);
    }

    /**
     * 设置全路径
     */
    private void settingsFullIds(RuleMenu old, RuleMenu ruleMenu) {

        if (old != null && ruleMenu.getParentId().equals(old.getParentId())) {

            return;
        }

        RuleMenu parent = null;

        // 最顶级目录
        if (StrUtil.isNotBlank(ruleMenu.getParentId())) {

            // 根据父节点查询数据
            parent = super.getById(ruleMenu.getParentId(), true);
        }

        StringBuilder allParentIds = new StringBuilder();

        BigDecimal level = BigDecimal.ZERO;

        if (parent != null) {

            allParentIds.append(parent.getAllParentIds());
            allParentIds.append(CommConstant.CONTENT_SPLIT);

            level = parent.getLevel();

            // 当前选择的上一层级节点数加1
            parent.setChildQty(parent.getChildQty().add(BigDecimal.ONE));

            super.store(parent);
        }

        allParentIds.append(ruleMenu.getId());
        ruleMenu.setAllParentIds(allParentIds.toString());

        // 设置层级结构
        ruleMenu.setLevel(level.add(BigDecimal.ONE));

        super.store(ruleMenu);

        if (old != null && StrUtil.isNotBlank(old.getParentId())) {

            RuleMenu oldParent = this.getById(old.getParentId());

            // 旧的父记录减1
            oldParent.setChildQty(oldParent.getChildQty().subtract(BigDecimal.ONE));
            super.store(oldParent);
        }
    }

    /**
     * 查询规则菜单表详情
     */
    @Override
    public RuleMenu viewRuleMenu(String id) {

        RuleMenu entity = super.getById(id, true);

        return entity;
    }

    /**
     * 删除规则菜单表记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRuleMenu(String id) {

        // 查询旧记录
        RuleMenu old = super.getById(id);

        super.deleteBy(id);

        // 更新上一级子节点数
        RuleMenu parent = super.getById(old.getParentId());

        parent.setChildQty(parent.getChildQty().subtract(BigDecimal.ONE));

        super.store(parent);
    }
}
